import React, { useState, useEffect } from 'react';
import { Form, Input, InputNumber, Switch, Slider, Card, Space, Row, Col, Typography, Radio, Button, message, Select, ConfigProvider, theme } from 'antd';
import { useSelector } from 'react-redux';
import { selectSelectedSegment, SelectedSegmentInfo } from '@/store/selectedSegmentSlice';
import { getOperationTypes, updateSegmentVideoOperations, getSegmentOperations } from '../../services/project';
import '@/styles/BaseConfigForm.css';
import eventBus from '@/utils/eventBus';
import { createDebounce } from '@/utils/debounceUtils';
import Operation from 'antd/es/transfer/operation';

// 操作类型定义
interface Operation {
    operation_type: string;
    params: any;
}

interface OperationsData {
    operations: Operation[];
}

const { Text } = Typography;

// 深色主题配置
const darkTheme = {
    algorithm: theme.darkAlgorithm,
    token: {
        colorPrimary: '#715BB8',
        colorBgContainer: '#1f1f1f',
        colorBgElevated: '#2a2a2a',
        colorText: '#ffffff',
        colorTextSecondary: 'rgba(255, 255, 255, 0.7)',
        colorBorder: '#434343',
        borderRadius: 6,
    },
    components: {
        Card: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
        },
        InputNumber: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
        },
        Radio: {
            buttonSolidCheckedBg: '#715BB8',
            buttonSolidCheckedColor: '#ffffff',
            buttonBg: '#2a2a2a',
            buttonColor: '#ffffff',
            buttonCheckedBg: '#715BB8',
            buttonCheckedColor: '#ffffff',
        },
        Slider: {
            railBg: '#555555',
            trackBg: '#715BB8',
            handleColor: '#3C3C3C',
            handleBorderColor: '#ffffff',
        },
    },
};

// 辅助组件：用于创建标签-滑块-数值输入的组合行
const SliderInputRow: React.FC<{
    label: string;
    name: string[];
    sliderProps: any;
    inputProps: any;
}> = ({ label, name, sliderProps, inputProps }) => (
    <Form.Item>
        <Row align="middle" gutter={16}>
            <Col span={6}>
                <Text className="slider-label">{label}</Text>
            </Col>
            <Col span={12}>
                <Form.Item name={name} noStyle>
                    <Slider {...sliderProps} />
                </Form.Item>
            </Col>
            <Col span={6}>
                <Form.Item name={name} noStyle>
                    <InputNumber className="slider-input-number" {...inputProps} />
                </Form.Item>
            </Col>
        </Row>
    </Form.Item>
);

// 表单数据接口
interface BaseConfigFormData extends SelectedSegmentInfo {
    operations: OperationsData;
}

const BaseConfigForm: React.FC = () => {
    const [form] = Form.useForm();
    // 动画选项状态管理
    const [introOptions, setIntroOptions] = useState<{ label: string; value: string }[]>([]);
    const [outroOptions, setOutroOptions] = useState<{ label: string; value: string }[]>([]);
    // 是否循环动画
    const [loopOptions, setLoopOptions] = useState<{ label: string; value: string }[]>([]);
    const [loopAnimation, setLoopAnimation] = useState(false);
    const [selectedLoopAnimation, setSelectedLoopAnimation] = useState<string | undefined>(undefined);
    // 滤镜选项状态管理
    const [filterOptions, setFilterOptions] = useState<{ label: string; value: string }[]>([]);
    // 特效选项状态管理
    const [effectOptions, setEffectOptions] = useState<{ label: string; value: string }[]>([]);
    // 转场选项状态管理
    const [transitionOptions, setTransitionOptions] = useState<{ label: string; value: string }[]>([]);
    // 蒙版选项状态管理
    const [maskOptions, setMaskOptions] = useState<{ label: string; value: string }[]>([]);

    const selectedSegment = useSelector(selectSelectedSegment);

    // 获取素材操作信息并设置表单默认值
    useEffect(() => {
        if (selectedSegment && selectedSegment.draftId && selectedSegment.trackId && selectedSegment.id) {
            getSegmentOperations(selectedSegment.draftId, selectedSegment.trackId, selectedSegment.id)
                .then((response) => {
                    const data = response;

                    if (data.data && data.data.operations) {
                        const operations = data.data.operations;
                        const formValues: any = {};

                        // 处理入场动画
                        const introAnimation = operations.find((op: any) => op.operation_type === 'animation' && op.params.animation_category === 'intro');
                        if (introAnimation) {
                            formValues.animations_instance = {
                                ...formValues.animations_instance,
                                intro_animations: introAnimation.params.animation_type.toLowerCase().replace(/\s+/g, '_'),
                                intro_duration: parseFloat(introAnimation.params.duration.replace('s', '')),
                            };
                        }

                        // 处理出场动画
                        const outroAnimation = operations.find((op: any) => op.operation_type === 'animation' && op.params.animation_category === 'outro');
                        if (outroAnimation) {
                            formValues.animations_instance = {
                                ...formValues.animations_instance,
                                outro_animations: outroAnimation.params.animation_type.toLowerCase().replace(/\s+/g, '_'),
                                outro_duration: parseFloat(outroAnimation.params.duration.replace('s', '')),
                            };
                        }

                        // 处理循环动画
                        const loopAnimationOp = operations.find((op: any) => op.operation_type === 'animation' && op.params.animation_category === 'loop');
                        if (loopAnimationOp) {
                            setLoopAnimation(true);
                            setSelectedLoopAnimation(loopAnimationOp.params.animation_type.toLowerCase().replace(/\s+/g, '_'));
                        }

                        // 处理背景填充
                        const backgroundFilling = operations.find((op: any) => op.operation_type === 'background_filling');
                        if (backgroundFilling) {
                            formValues.background_filling = {
                                fill_type: backgroundFilling.params.fill_type,
                                blur_amount: backgroundFilling.params.blur_amount,
                                color: backgroundFilling.params.color,
                            };
                        }

                        // 处理特效
                        const effect = operations.find((op: any) => op.operation_type === 'effect');
                        if (effect) {
                            formValues.video_effects = effect.params.effect_type.toLowerCase().replace(/\s+/g, '_');
                            formValues.effect_intensity = effect.params.effect_params[0];
                        }

                        // 处理滤镜
                        const filter = operations.find((op: any) => op.operation_type === 'filter');
                        if (filter) {
                            formValues.filters = filter.params.filter_type.toLowerCase().replace(/\s+/g, '_');
                            formValues.filter_intensity = filter.params.filter_params.intensity * 100;
                        }

                        // 处理关键帧
                        const keyframe = operations.find((op: any) => op.operation_type === 'keyframe');
                        if (keyframe) {
                            formValues.keyframe = {
                                attribute: keyframe.params.attribute,
                                time_offset: keyframe.params.time_offset,
                                value: keyframe.params.value,
                            };
                        }

                        // 处理蒙版
                        const mask = operations.find((op: any) => op.operation_type === 'mask');
                        if (mask) {
                            formValues.masks = mask.params.mask_type.toLowerCase().replace(/\s+/g, '_');
                            formValues.mask_aspect_ratio = mask.params.aspect_ratio || 1.0;
                            formValues.mask_position_x = mask.params.center_x;
                            formValues.mask_position_y = mask.params.center_y;
                            formValues.mask_size = mask.params.size;
                            formValues.mask_rotation = mask.params.rotation;
                            formValues.mask_feather = mask.params.feather;
                            formValues.mask_invert = mask.params.invert;
                        }

                        // 处理转场
                        const transition = operations.find((op: any) => op.operation_type === 'transition');
                        if (transition) {
                            formValues.transitions = transition.params.transition_type.toLowerCase().replace(/\s+/g, '_');
                            formValues.transition_duration = parseFloat(transition.params.duration.replace('s', '')) * 1000000;
                            formValues.transition_overlap = transition.params.overlap || false;
                        }

                        // 设置表单值
                        form.setFieldsValue(formValues);
                    }
                })
                .catch((error) => {
                    console.error('获取素材操作信息失败:', error);
                });
        }
    }, [selectedSegment, form]);

    // 获取动画和滤镜数据 - 并行调用
    useEffect(() => {
        // 并行调用获取动画和滤镜数据的接口
        const fetchAnimationData = () => {
            return getOperationTypes('animation')
                .then((response) => {
                    const data = response;

                    if (data.data && data.data.operation_info) {
                        const { intro, outro, loop } = data.data.operation_info;
                        const segmentType = selectedSegment?.type;

                        // 根据片段类型选择相应的动画类型
                        const introTypes = segmentType === 'text' ? intro?.text_types : intro?.video_types;
                        const outroTypes = segmentType === 'text' ? outro?.text_types : outro?.video_types;
                        const loopTypes = loop?.text_types || [];

                        // 转换入场动画数据格式 - 字符串数组转对象数组
                        const newIntroOptions =
                            introTypes?.map((type: string) => ({
                                label: type,
                                value: type.toLowerCase().replace(/\s+/g, '_'),
                            })) || [];

                        // 转换出场动画数据格式 - 字符串数组转对象数组
                        const newOutroOptions =
                            outroTypes?.map((type: string) => ({
                                label: type,
                                value: type.toLowerCase().replace(/\s+/g, '_'),
                            })) || [];

                        // 转换循环动画数据格式 - 字符串数组转对象数组
                        const newLoopOptions =
                            loopTypes?.map((type: string) => ({
                                label: type,
                                value: type.toLowerCase().replace(/\s+/g, '_'),
                            })) || [];

                        // 使用 setState 更新状态
                        setIntroOptions(newIntroOptions);
                        setOutroOptions(newOutroOptions);
                        setLoopOptions(newLoopOptions);
                    }
                })
                .catch((error) => {
                    console.error('获取动画数据失败:', error);
                });
        };

        const fetchFilterData = () => {
            return getOperationTypes('filter')
                .then((response) => {
                    const data = response;

                    if (data.data && data.data.operation_info) {
                        const { types } = data.data.operation_info;

                        // 转换滤镜数据格式
                        const newFilterOptions =
                            types?.map((type: string) => ({
                                label: type,
                                value: type.toLowerCase().replace(/\s+/g, '_'),
                            })) || [];

                        // 使用 setState 更新状态
                        setFilterOptions(newFilterOptions);
                    }
                })
                .catch((error) => {
                    console.error('获取滤镜数据失败:', error);
                });
        };

        const fetchEffectData = () => {
            return getOperationTypes('effect')
                .then((response) => {
                    const data = response;

                    if (data.data && data.data.operation_info) {
                        const { types } = data.data.operation_info;

                        // 转换特效数据格式
                        const newEffectOptions =
                            types?.map((type: string) => ({
                                label: type,
                                value: type.toLowerCase().replace(/\s+/g, '_'),
                            })) || [];

                        // 使用 setState 更新状态
                        setEffectOptions(newEffectOptions);
                    }
                })
                .catch((error) => {
                    console.error('获取特效数据失败:', error);
                });
        };

        const fetchTransitionData = () => {
            return getOperationTypes('transition')
                .then((response) => {
                    const data = response;

                    if (data.data && data.data.operation_info) {
                        const { types } = data.data.operation_info;

                        // 转换转场数据格式
                        const newTransitionOptions =
                            types?.map((type: string) => ({
                                label: type,
                                value: type.toLowerCase().replace(/\s+/g, '_'),
                            })) || [];

                        // 使用 setState 更新状态
                        setTransitionOptions(newTransitionOptions);
                    }
                })
                .catch((error) => {
                    console.error('获取转场数据失败:', error);
                });
        };

        const fetchMaskData = () => {
            return getOperationTypes('mask')
                .then((response) => {
                    const data = response;

                    if (data.data && data.data.operation_info) {
                        const { types } = data.data.operation_info;

                        // 转换蒙版数据格式
                        const newMaskOptions =
                            types?.map((type: string) => ({
                                label: type,
                                value: type.toLowerCase().replace(/\s+/g, '_'),
                            })) || [];

                        // 使用 setState 更新状态
                        setMaskOptions(newMaskOptions);
                    }
                })
                .catch((error) => {
                    console.error('获取蒙版数据失败:', error);
                });
        };

        // 立即执行各个数据获取函数
        const animationPromise = fetchAnimationData();
        const filterPromise = fetchFilterData();
        const effectPromise = fetchEffectData();
        const transitionPromise = fetchTransitionData();
        const maskPromise = fetchMaskData();

        // 并行执行所有请求
        Promise.all([animationPromise, filterPromise, effectPromise, transitionPromise, maskPromise]).catch((error) => {
            console.error('获取媒体效果数据失败:', error);
        });
    }, []);

    const handleValuesChange = (changedValues: any, allValues: any) => {
        // 从allValues中提取数据并构建operations数组
        const operations: Operation[] = [];
        const segmentType = selectedSegment?.type;

        // 1. 处理入场动画
        const introAnimationValue = allValues?.animations_instance?.intro_animations;
        const introDuration = allValues?.animations_instance?.intro_duration ? `${allValues.animations_instance.intro_duration}s` : '1.5s';
        if (introAnimationValue) {
            const introOption = introOptions.find((opt) => opt.value === introAnimationValue);
            if (introOption) {
                operations.push({
                    operation_type: 'animation',
                    params: {
                        animation_category: 'intro',
                        animation_type: introOption.label,
                        duration: introDuration,
                        media_type: segmentType, // 添加媒体类型
                    },
                });
            }
        }

        // 2. 处理出场动画
        const outroAnimationValue = allValues?.animations_instance?.outro_animations;
        const outroDuration = allValues?.animations_instance?.outro_duration ? `${allValues.animations_instance.outro_duration}s` : '1.5s';
        if (outroAnimationValue) {
            const outroOption = outroOptions.find((opt) => opt.value === outroAnimationValue);
            if (outroOption) {
                operations.push({
                    operation_type: 'animation',
                    params: {
                        animation_category: 'outro',
                        animation_type: outroOption.label,
                        duration: outroDuration,
                        media_type: segmentType, // 添加媒体类型
                    },
                });
            }
        }

        // 3. 处理循环动画
        if (loopAnimation && selectedLoopAnimation) {
            const loopOption = loopOptions.find((opt) => opt.value === selectedLoopAnimation);
            if (loopOption) {
                operations.push({
                    operation_type: 'animation',
                    params: {
                        animation_category: 'loop',
                        animation_type: loopOption.label,
                        media_type: 'text', // 循环动画仅支持文本
                    },
                });
            }
        }

        // 3. 处理背景填充
        const fillType = allValues?.background_filling?.fill_type;
        if (fillType && fillType !== 'none') {
            operations.push({
                operation_type: 'background_filling',
                params: {
                    fill_type: fillType || 'blur',
                    blur_amount: allValues?.background_filling?.blur_amount || 0.0625,
                    color: allValues?.background_filling?.color || '#FF0000',
                },
            });
        }

        // 4. 处理特效
        const videoEffectValue = allValues?.video_effects;
        const effectIntensity = allValues?.effect_intensity || 0.5;
        if (videoEffectValue) {
            const effectOption = effectOptions.find((opt) => opt.value === videoEffectValue);
            if (effectOption) {
                operations.push({
                    operation_type: 'effect',
                    params: {
                        effect_type: effectOption.label,
                        effect_params: [effectIntensity, 1.0],
                    },
                });
            }
        }

        // 5. 处理滤镜
        const filterValue = allValues?.filters;
        const filterIntensity = allValues?.filter_intensity || 0.8;
        if (filterValue) {
            const filterOption = filterOptions.find((opt) => opt.value === filterValue);
            if (filterOption) {
                operations.push({
                    operation_type: 'filter',
                    params: {
                        filter_type: filterOption.label,
                        filter_params: {
                            intensity: filterIntensity,
                        },
                    },
                });
            }
        }

        // 6. 处理关键帧
        const keyframeAttribute = allValues?.keyframe?.attribute;
        if (keyframeAttribute) {
            operations.push({
                operation_type: 'keyframe',
                params: {
                    attribute: keyframeAttribute,
                    time_offset: allValues?.keyframe?.time_offset || 2.5,
                    value: allValues?.keyframe?.value || 0.8,
                },
            });
        }

        // 7. 处理蒙版
        const maskValue = allValues?.masks;
        if (maskValue) {
            const maskOption = maskOptions.find((opt) => opt.value === maskValue);
            if (maskOption) {
                operations.push({
                    operation_type: 'mask',
                    params: {
                        mask_type: maskOption.label,
                        center_x: allValues?.mask_position_x || 0.5,
                        center_y: allValues?.mask_position_y || 0.5,
                        size: allValues?.mask_size || 50.0,
                        rotation: allValues?.mask_rotation || 0.0,
                        feather: allValues?.mask_feather || 0.0,
                        invert: allValues?.mask_invert || false,
                    },
                });
            }
        }

        // 8. 处理转场
        const transitionValue = allValues?.transitions;
        if (transitionValue) {
            const transitionOption = transitionOptions.find((opt) => opt.value === transitionValue);
            if (transitionOption) {
                const transitionDuration = allValues?.transition_duration;
                const durationInSeconds = transitionDuration ? `${transitionDuration / 1000000}s` : '1s';
                operations.push({
                    operation_type: 'transition',
                    params: {
                        transition_type: transitionOption.label,
                        duration: durationInSeconds,
                        overlap: allValues?.transition_overlap || false,
                    },
                });
            }
        }

        // 构建最终的operationsData对象
        const operationsData = {
            operations: operations.filter((op) => op), // 过滤掉undefined的操作
        };

        // 只有在表单值真正发生变化时才发送事件
        // 避免在Tab切换或初始化时触发
        if (Object.keys(changedValues).length > 0) {
            // 构建保存数据
            const saveData = {
                draftId: selectedSegment.draftId,
                trackId: selectedSegment.trackId,
                id: selectedSegment.id,
                material_id: selectedSegment.material_id,
                operations: operationsData,
            };

            // 发送表单数据到事件总线
            (eventBus as any).emit('form:data:changed', {
                segmentId: selectedSegment.id,
                formData: saveData,
                formType: 'base',
            });
        }
    };

    // 根据片段类型判断是否显示某个卡片
    const shouldShowCard = (cardType: string) => {
        if (!selectedSegment) return false;

        const segmentType = selectedSegment.type;

        switch (cardType) {
            case 'animations':
                // 动画对所有类型都显示
                return true;
            case 'background_filling':
            case 'effects':
            case 'filters':
            case 'transitions':
            case 'masks':
                // 背景填充、特效、滤镜、转场、蒙版只对视频显示
                return segmentType === 'video';
            default:
                return false;
        }
    };

    const handleRandomTransition = () => {
        if (transitionOptions && transitionOptions.length > 0) {
            // 随机选择一个转场效果
            const operations: Operation[] = [];
            const randomIndex = Math.floor(Math.random() * transitionOptions.length);
            const selectedTransition = transitionOptions[randomIndex];

            // 创建operations数组，包含一个transition对象
            operations.push({
                operation_type: 'transition',
                params: {
                    transition_type: selectedTransition.value,
                    duration: '1s',
                },
            });
            const operationsData = {
                operations: operations,
            };

            // 构建更新对象
            const updatedOperations = {
                draftId: selectedSegment.draftId,
                trackId: selectedSegment.trackId,
                id: selectedSegment.id,
                material_id: selectedSegment.material_id,
                operations: operationsData,
            };

            // 调用更新接口
            // debouncedUpdateSegment.execute(updatedOperations);
        }
    };

    return (
        <ConfigProvider theme={darkTheme}>
            <div className="base-config-form">
                <Form form={form} layout="vertical" onValuesChange={handleValuesChange} size="small">
                    {/* 动画设置 - 对所有类型显示 */}
                    {shouldShowCard('animations') && (
                        <Card title="动画设置" size="small" className="form-card">
                            {/* 入场动画 */}
                            <div className="animation-section">
                                <Row align="middle" gutter={16} className="animation-header">
                                    <Col flex="auto">
                                        <Text className="animation-title">入场动画</Text>
                                    </Col>
                                </Row>
                                <Form.Item name={['animations_instance', 'intro_animations']} noStyle>
                                    {introOptions.length > 0 ? <Select placeholder="请选择入场动画" className="animation-select" options={introOptions} /> : <Text type="secondary">加载中...</Text>}
                                </Form.Item>
                                <Form.Item label="入场动画时长" name={['animations_instance', 'intro_duration']}>
                                    <InputNumber min={0.1} max={5} step={0.1} placeholder="时长（秒）" className="duration-input" />
                                </Form.Item>
                            </div>

                            {/* 出场动画 */}
                            <div className="animation-section">
                                <Row align="middle" gutter={16} className="animation-header">
                                    <Col flex="auto">
                                        <Text className="animation-title">出场动画</Text>
                                    </Col>
                                </Row>
                                <Form.Item name={['animations_instance', 'outro_animations']} noStyle>
                                    {outroOptions.length > 0 ? <Select placeholder="请选择出场动画" className="animation-select" options={outroOptions} /> : <Text type="secondary">加载中...</Text>}
                                </Form.Item>
                                <Form.Item label="出场动画时长" name={['animations_instance', 'outro_duration']}>
                                    <InputNumber min={0.1} max={5} step={0.1} placeholder="时长（秒）" className="duration-input" />
                                </Form.Item>
                            </div>

                            {/* 循环动画设置 - 仅对文本显示 */}
                            {selectedSegment?.type === 'text' && (
                                <div className="animation-section">
                                    <Form.Item label="循环动画" valuePropName="checked">
                                        <Switch
                                            checked={loopAnimation}
                                            onChange={(checked) => {
                                                setLoopAnimation(checked);
                                            }}
                                            checkedChildren="开启"
                                            unCheckedChildren="关闭"
                                        />
                                    </Form.Item>

                                    {loopAnimation && (
                                        <>
                                            <Row align="middle" gutter={16} className="animation-header">
                                                <Col flex="auto">
                                                    <Text className="animation-title">循环动画效果</Text>
                                                </Col>
                                            </Row>
                                            <Form.Item name="selectedLoopAnimation" noStyle>
                                                <Select
                                                    placeholder="请选择循环动画"
                                                    className="animation-select"
                                                    options={loopOptions}
                                                    defaultValue={loopOptions[0]?.value}
                                                    onChange={(value) => {
                                                        form.setFieldValue('selectedLoopAnimation', value);
                                                    }}
                                                />
                                            </Form.Item>
                                        </>
                                    )}
                                </div>
                            )}
                        </Card>
                    )}

                    {/* 背景填充设置 - 只对视频显示 */}
                    {shouldShowCard('background_filling') && (
                        <Card title="背景填充设置" size="small" className="form-card">
                            <Form.Item label="填充类型" name={['background_filling', 'fill_type']}>
                                <Radio.Group buttonStyle="solid">
                                    <Space wrap size="small">
                                        <Radio.Button value="blur">模糊</Radio.Button>
                                        <Radio.Button value="color">纯色</Radio.Button>
                                        <Radio.Button value="none">无</Radio.Button>
                                    </Space>
                                </Radio.Group>
                            </Form.Item>

                            <Form.Item shouldUpdate={(prevValues, currentValues) => prevValues.background_filling?.fill_type !== currentValues.background_filling?.fill_type}>
                                {({ getFieldValue }) => {
                                    const fillType = getFieldValue(['background_filling', 'fill_type']);
                                    return (
                                        <Row gutter={16}>
                                            {/* 根据填充类型动态显示模糊程度控件 */}
                                            {fillType === 'blur' && (
                                                <Col span={12}>
                                                    <Form.Item label="模糊程度" name={['background_filling', 'blur_amount']}>
                                                        <SliderInputRow
                                                            name={['background_filling', 'blur_amount']}
                                                            label="模糊强度"
                                                            sliderProps={{ min: 0, max: 1, step: 0.01 }}
                                                            inputProps={{ min: 0, max: 1, step: 0.01 }}
                                                        />
                                                    </Form.Item>
                                                </Col>
                                            )}

                                            {/* 根据填充类型动态显示填充颜色控件 */}
                                            {fillType === 'color' && (
                                                <Col span={12}>
                                                    <Form.Item label="填充颜色" name={['background_filling', 'color']}>
                                                        <Input type="color" defaultValue="#FF0000" className="color-input" />
                                                    </Form.Item>
                                                </Col>
                                            )}
                                        </Row>
                                    );
                                }}
                            </Form.Item>
                        </Card>
                    )}

                    {/* 关键帧设置 - 对视频显示
        {shouldShowCard('effects') && (
          <Card title="关键帧设置" size="small" style={{ marginBottom: 16 }} className={'form-card'}>
            <Row align="middle" gutter={16} style={{ marginBottom: 12 }}>
              <Col flex="auto">
                <Typography.Text style={{ color: '#FFFFFF', fontWeight: 'bold' }}>属性选择</Typography.Text>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item name={['keyframe', 'attribute']} noStyle>
                  <Radio.Group buttonStyle="solid">
                    <Space wrap size="small">
                      <Radio.Button value="opacity">透明度</Radio.Button>
                      <Radio.Button value="position">位置</Radio.Button>
                      <Radio.Button value="scale">缩放</Radio.Button>
                    </Space>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="时间偏移（秒）" name={['keyframe', 'time_offset']}>
                  <InputNumber
                    min={0}
                    max={60}
                    step={0.1}
                    placeholder="时间偏移"
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="值" name={['keyframe', 'value']}>
                  <InputNumber
                    min={0}
                    max={1}
                    step={0.01}
                    placeholder="属性值"
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Card>
        )} */}

                    {/* 特效设置 - 只对视频显示 */}
                    {shouldShowCard('effects') && (
                        <Card title="特效设置" size="small" className="form-card">
                            <Row align="middle" gutter={16} className="effect-header">
                                <Col flex="auto">
                                    <Text className="effect-title">视频特效</Text>
                                </Col>
                            </Row>
                            <Form.Item name="video_effects" noStyle>
                                {effectOptions.length > 0 ? <Select placeholder="请选择视频特效" className="animation-select" options={effectOptions} /> : <Text type="secondary">加载中...</Text>}
                            </Form.Item>

                            <SliderInputRow label="特效强度" name={['effect_intensity']} sliderProps={{ min: 0, max: 100, step: 1 }} inputProps={{ min: 0, max: 100, step: 1 }} />
                        </Card>
                    )}

                    {/* 滤镜设置 - 只对视频显示 */}
                    {shouldShowCard('filters') && (
                        <Card title="滤镜设置" size="small" className="form-card">
                            <Row align="middle" gutter={16} className="filter-header">
                                <Col flex="auto">
                                    <Text className="filter-title">滤镜效果</Text>
                                </Col>
                            </Row>
                            <Form.Item name="filters" noStyle>
                                {filterOptions.length > 0 ? <Select placeholder="请选择滤镜效果" className="animation-select" options={filterOptions} /> : <Text type="secondary">加载中...</Text>}
                            </Form.Item>

                            <SliderInputRow label="滤镜强度" name={['filter_intensity']} sliderProps={{ min: 0, max: 100, step: 1 }} inputProps={{ min: 0, max: 100, step: 1 }} />
                        </Card>
                    )}

                    {/* 转场设置 - 只对视频显示 */}
                    {shouldShowCard('transitions') && (
                        <Card title="转场设置" size="small" className="form-card">
                            <Row align="middle" gutter={16} className="transition-header">
                                <Col flex="auto">
                                    <Text className="transition-title">转场效果</Text>
                                </Col>
                                <Col>
                                    <Button type="primary" onClick={() => handleRandomTransition()}>
                                        随机
                                    </Button>
                                </Col>
                            </Row>
                            <Form.Item name="transitions" noStyle>
                                {transitionOptions.length > 0 ? <Select placeholder="请选择转场效果" className="animation-select" options={transitionOptions} /> : <Text type="secondary">加载中...</Text>}
                            </Form.Item>

                            <Row gutter={16}>
                                <Col span={12}>
                                    <Form.Item label="转场时长（微秒）" name={['transition_duration']}>
                                        <InputNumber min={100000} max={5000000} step={100000} placeholder="转场时长" className="transition-duration-input" />
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label="是否重叠" name={['transition_overlap']} valuePropName="checked">
                                        <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Card>
                    )}

                    {/* 蒙版设置 - 只对视频显示 */}
                    {shouldShowCard('masks') && (
                        <Card title="蒙版设置" size="small" className="form-card">
                            <Row align="middle" gutter={16} className="mask-header">
                                <Col flex="auto">
                                    <Text className="mask-title">蒙版效果</Text>
                                </Col>
                            </Row>
                            <Form.Item name="masks" noStyle>
                                {maskOptions.length > 0 ? <Select placeholder="请选择蒙版效果" className="animation-select" options={maskOptions} /> : <Text type="secondary">加载中...</Text>}
                            </Form.Item>

                            <SliderInputRow label="蒙版宽高比" name={['mask_aspect_ratio']} sliderProps={{ min: 0, max: 1.0, step: 0.01 }} inputProps={{ min: 0, max: 1.0, step: 0.01 }} />

                            <SliderInputRow label="蒙版X位置" name={['mask_position_x']} sliderProps={{ min: 0, max: 1, step: 0.01 }} inputProps={{ min: 0, max: 1, step: 0.01 }} />

                            <SliderInputRow label="蒙版Y位置" name={['mask_position_y']} sliderProps={{ min: 0, max: 1, step: 0.01 }} inputProps={{ min: 0, max: 1, step: 0.01 }} />

                            <SliderInputRow label="蒙版大小" name={['mask_size']} sliderProps={{ min: 0, max: 1, step: 0.01 }} inputProps={{ min: 0, max: 1, step: 0.01 }} />

                            <SliderInputRow label="蒙版旋转角度" name={['mask_rotation']} sliderProps={{ min: 0, max: 360, step: 1 }} inputProps={{ min: 0, max: 360, step: 1 }} />

                            <SliderInputRow label="蒙版羽化值" name={['mask_feather']} sliderProps={{ min: 0, max: 1, step: 0.01 }} inputProps={{ min: 0, max: 1, step: 0.01 }} />
                        </Card>
                    )}

                    {/* 如果没有选中片段或者是文字类型且不显示任何卡片时的提示 */}
                    {!selectedSegment && (
                        <Card size="small" className="form-card">
                            <Text className="no-segment-text">请先选择一个片段</Text>
                        </Card>
                    )}

                    {selectedSegment && selectedSegment.type === 'text' && !shouldShowCard('animations') && (
                        <Card size="small" className="form-card">
                            <Text className="no-segment-text">文字片段暂无可配置项</Text>
                        </Card>
                    )}
                </Form>

                <style>{`
          .base-config-form {
            height: 100%;
            overflow: auto;
          }
          
          .form-card {
            margin-bottom: 16px;
          }
          
          .animation-section {
            margin-bottom: 24px;
          }
          
          .animation-header {
            margin-bottom: 12px;
          }
          
          .animation-title {
            font-weight: bold;
            margin-right: 8px;
          }
          
          .animation-select {
            width: 100%;
          }
          
          .duration-input {
            width: 100%;
          }
          
          .color-input {
            height: 32px;
          }
          
          .effect-header,
          .filter-header,
          .transition-header,
          .mask-header {
            margin-bottom: 12px;
          }
          
          .effect-title,
          .filter-title,
          .transition-title,
          .mask-title {
            font-weight: bold;
          }
          
          .radio-group-space {
            width: 100%;
          }
          
          .transition-duration-input {
            width: 100%;
          }
          
          .no-segment-text {
            color: #ffffff;
          }
          
          .slider-label {
            color: #ffffff;
          }
          
          .slider-input-number {
            width: 90%;
          }
        `}</style>
            </div>
        </ConfigProvider>
    );
};

export default BaseConfigForm;
export type { BaseConfigFormData };
